//
//  SendListViewController.m
//  SafeFoodManagerDemo
//
//  Created by bob on 2017/10/31.
//  Copyright © 2017年 bob. All rights reserved.
//

#import "SendListViewController.h"
#import "MsgReceiveModel.h"
#import "MsgTableViewCell.h"
#import "MsgHeadView.h"
#import "MsgDetialViewController.h"
#import "MsgDetailModel.h"
@interface SendListViewController ()

@end

@implementation SendListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title=@"发件箱";
    
    self.homeTableView.estimatedRowHeight=90;
    
    self.view.backgroundColor=TBColorTableViewBg;
    
     self.homeTableView.frame=CGRectMake(15, self.homeTableView.frame.origin.y, SCREEN_WIDTH-30, self.homeTableView.frame.size.height);
    
    [self.homeTableView registerNib:[UINib nibWithNibName:@"MsgTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    
    [self.homeTableView registerClass:[MsgHeadView class] forHeaderFooterViewReuseIdentifier:@"head"];
    
    [self.homeTableView.mj_header beginRefreshing];
    
    // Do any additional setup after loading the view.
}

#pragma mark-tablevie代理方法

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return self.dataArr.count;
    
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return 1;
    
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MsgRecriveData *data=self.dataArr[indexPath.section];

        MsgTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        
        cell.isClick=self.isEdit;
        
        cell.deleStatue=self.deleStatue;//是否编辑状态
        
        cell.model=data;
        
        return cell;
 
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    return UITableViewAutomaticDimension;

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

        MsgRecriveData *data=self.dataArr[indexPath.section];
        
        if (self.deleStatue) {
            
            data.Select=!data.Select;
            
            [self ChangeStatues];
            
            [self.homeTableView reloadData];
            
            
        }else{
            
            //查看消息详情
            
            MsgDetailModel *model=[MsgDetailModel new];
            
            model.msgId=data.ID;
            
            model.loginType=[self getUserType];
            
            if ([self getUserType]==1) {
                
                model.readerId=[LoginStatuesModel shopId];
                
            }else{
                
                model.readerId=[LoginStatuesModel getStaffId];
                
            }
   
            MsgDetialViewController *detial=[MsgDetialViewController new];
            
            detial.Reqmodel=model;
            
            detial.block=^()
            {
                
            };
            
            [self.navigationController pushViewController:detial animated:YES];
     
        }
}


-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return YES;
}


-(NSString*)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return @"删除";
    
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return UITableViewCellEditingStyleDelete;
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return 42;
}


-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    MsgRecriveData *data=self.dataArr[section];
    
    MsgHeadView *head=[tableView dequeueReusableHeaderFooterViewWithIdentifier:@"head"];
    
    head.timeStr=data.sendTime;
    
    return head;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (editingStyle==UITableViewCellEditingStyleDelete) {
        
        MsgRecriveData *data=self.dataArr[indexPath.section];
        
        NSMutableArray *arr=[NSMutableArray array];
        
        [arr addObject:[NSString stringWithFormat:@"%ld",data.ID]];
        
        [self DelPostion:arr];
        
    }
    
}


-(void)DelPostion:(NSArray*)PostID
{
    NSString *params=[HelpWay arrToJSON:PostID];
    
    [self showLoadingAnimation];
    
    NSString*deleid=@"";
    
    if ([self getUserType]==1) {
        
        deleid=[NSString stringWithFormat:@"%ld",[LoginStatuesModel shopId]];
    }else{
        
        deleid=[NSString stringWithFormat:@"%ld",[LoginStatuesModel getStaffId]];
        
    }
    
    BaseReqApi *api=[[BaseReqApi alloc]initWithRequestUrl:@"/index.php/FoodCheckApi/messageSendDel.json" andrequestTime:5 andParams:@{@"msgIds":params,@"senderId":deleid} andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:YES];
    
    [api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        [self stopLoadingAnimation];
        
        if (responseStatus==1) {
            
            [MBProgressHUD showSuccessMessage:@"删除成功"];
            
            [self.homeTableView.mj_header beginRefreshing];
            
            if (self.deleStatue) {
                //如果处于删除状态
                [self GotoEdit:self.btn];
            }
            
        }else if (responseStatus==0)
        {
            
            [MBProgressHUD showErrorMessage:message];
            
        }else if (responseStatus==2)
        {
            [MBProgressHUD showErrorMessage:message];
            
        }else{
            
            [UIAlertView bk_showAlertViewWithTitle:message message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                if (buttonIndex==1) {
                    
                    [self GotoLoginVC];
                }
                
            }];
            
        }
    }];
    
    
}


#pragma mark-跳转事件
-(void)PushChangeStatueVC
{
    
}
#pragma mark-编辑事件
-(void)GotoEdit:(UIButton*)sender
{
    sender.selected=!sender.selected;
    
    self.deleStatue=sender.selected;
    
    if (!self.deleStatue) {
        
        for (MsgRecriveData *data in self.dataArr) {
            
            data.Select=NO;
            
        }
        
        [self ChangeStatues];
    }
    
    [self.homeTableView reloadData];
}


-(void)SeletAll
{
    
    for (MsgRecriveData *data in self.dataArr) {
        
        data.Select=YES;
        
    }
    
    [self ChangeStatues];
    [self.homeTableView reloadData];
    
}//全选

-(void)CanseletAll{
    
    for (MsgRecriveData *data in self.dataArr) {
        
        data.Select=NO;
        
    }
    
    [self ChangeStatues];
    [self.homeTableView reloadData];
    
}//取消全选

-(void)DelectAll
{
    NSMutableArray *arr=[NSMutableArray array];
    
    for ( MsgRecriveData *data in self.dataArr) {
        
        if (data.Select) {
            
            [arr addObject:[NSString stringWithFormat:@"%ld",data.ID]];
            
        }
        
    }
    
    if (arr.count==0) {
        
        [MBProgressHUD showWarnMessage:@"请至少选择一项"];
        
        return;
    }
    
    [self DelPostion:arr];
}//全部删除


-(void)ChangeStatues{
    
    NSInteger i=0;
    
    for (MsgRecriveData *data in self.dataArr) {
        
        if (data.Select) {
            i++;
        }
    }
    
    [self.DeleView SelectNum:i];
}



#pragma mark-空白页点击事件
- (void)actionTapEmptyDataSetNodataView
{
    [self.homeTableView.mj_header beginRefreshing];
    
}


/**
 *  MJ头部刷新(封装层方法, 需要子类继承或者重写)
 */
- (void)actionMJHeaderRefresh
{
    self.Reqmodel.currentPage=1;
    
    [self.homeTableView.mj_footer resetNoMoreData];
    
    [self loadDatas];
}

/**
 *  MJ底部加载(封装方法, 需要子类继承或者重写)
 */
- (void)actionMJFooterLoadMore
{
    self.Reqmodel.currentPage++;
    
    [self loadDatas];
}

-(void)loadDatas
{
    [self showLoadingAnimation];
    
    BaseReqApi *api=[[BaseReqApi alloc]initWithRequestUrl:@"/index.php/FoodCheckApi/messageSendList.json" andrequestTime:5 andParams:self.Reqmodel.mj_keyValues andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:YES];
    
    [api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        [self stopLoadingAnimation];
        
        MsgReceiveModel *InforModel=[MsgReceiveModel mj_objectWithKeyValues:responseObject];
  
        if (responseStatus==1) {
            //请求成功
            
            NSLog(@"%@",[HelpWay dictionaryToJSON:responseObject]);
            
            self.TotalNum=[NSString stringWithFormat:@"一共找到%ld个%@",InforModel.totalRecord,@"消息"];
            
            if (InforModel.data.count==0&&self.Reqmodel.currentPage==1) {
                
                [self.dataArr removeAllObjects];
          
                self.homeTableView.frame=CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64);
                
                    self.Type=TBNODateType;
                
                [self.homeTableView reloadData];
            
                if (self.deleStatue) {
                    //如果处于删除状态
                    [self GotoEdit:self.btn];
                }
                self.btn.hidden=YES;
            }else if (InforModel.data.count==0&&self.Reqmodel.currentPage!=1){
                
                self.btn.hidden=NO;
                
                [self.homeTableView.mj_footer endRefreshingWithNoMoreData];
                
            } else{
                
                self.btn.hidden=NO;
                
                if (self.Reqmodel.currentPage==1) {
                    
                    [self.dataArr removeAllObjects];
                    
                }
                
                [self.dataArr addObjectsFromArray:InforModel.data];
                
                [self.homeTableView reloadData];
                
            }
            
            [self NetRequestSuccess:self scrollView:self.homeTableView];
            
        }else if (responseStatus==0||responseStatus==2)
        {
            if (self.Reqmodel.currentPage>1) {
                
                self.Reqmodel.currentPage=self.Reqmodel.currentPage-1;
            }
            
            [self NetRequestFail:self scrollView:self.homeTableView msg:message];
            
            self.Type=TBReqFalie;
            
        }else{
            //404需要重新登录了
            
            [UIAlertView bk_showAlertViewWithTitle:message message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                if (buttonIndex==1) {
                    
                    [self GotoLoginVC];
                }
                
            }];
        }
        
    }];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
